#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE PIPE_BUF

/**
 * Read from the fifo
 */
void *fifo_read(void* arg)
{
    int fifo_client;
    char buffer[BUFFER_SIZE];
    int ret;

    fifo_client = open((char*)arg, O_RDWR);
    if (fifo_client < 0)
            perror("open");

    while(1) {
        ret = read(fifo_client, buffer, BUFFER_SIZE * sizeof(char));
        if (ret < 0)
                perror("read");
        printf ("%s", buffer);
    }
}

/**
 * Write into the fifo
 */
void *fifo_write(void *arg)
{
    int fifo_client;
    char buffer[BUFFER_SIZE];
	char* tty = (char*) ttyname(0);
	int MAX_LINE = BUFFER_SIZE - strlen(tty) - 2;
    char read_line[MAX_LINE];

    fifo_client = open((char*)arg, O_WRONLY);
    if (fifo_client < 0)
        perror("open");

    while(1) {
		strcpy(buffer, tty);
		strcat(buffer, ": ");
        fgets(read_line, MAX_LINE * sizeof(char), stdin);
		strcat(buffer, read_line);

        int ret = write(fifo_client, buffer, BUFFER_SIZE * sizeof(char));
        if (ret < 0)
            perror("write");
    }
}

